import React, { useEffect, useState, useMemo, useRef, forwardRef, useImperativeHandle } from 'react';
import type { ProTableProps, ProTableRequestData, ProColumnsType, SearchRef } from './type';
import { Table } from 'antd';
import SearchBar from './SearchBar';
import TableHeader from './TableHeader';
import GlobalContext from './GlobalContext';
import Icon from '/@/components/icon';
import commonFunction from '/@/uilts/commonFunction';
const ProTable = forwardRef(function ProTable<T extends object>(
  {
    request,
    search = {
      searchText: '查询',
      resetText: '重置',
    },
    pagination = { pageSize: 10, current: 1 },
    columns,
    headerTitle,
    toolBarRender,
    ...tableProps
  }: ProTableProps<T>,
  ref: any
) {
  const [pageSize, setPageSize] = useState((pagination && pagination.pageSize) || 10);
  const [current, setCurrent] = useState((pagination && pagination.current) || 1);
  const [data, setdata] = useState<ProTableRequestData<T>>({
    total: 0,
    data: [],
  });
  const [tabLoading, setTabLoading] = useState<boolean>(true);
  useEffect(() => {
    //初始化调用查询，进行默认的值携带
    searchRef.current?.handleFormSubmit();
  }, []);
  const { copyText } = commonFunction();
  //发送请求并获取到数据赋值给data
  const reqFetch = async (
    params: {
      pageSize: number | undefined | any;
      current: number | undefined | any;
      [key: string]: any;
    },
    filters: any,
    sorter: any
  ) => {
    setTabLoading(true);
    const res = await request({ ...params }, filters, sorter);
    setdata(res);
    setTimeout(() => setTabLoading(false), 500);
  };
  //筛选出需要进行搜索的formItem
  const searchFormItem = useMemo<ProColumnsType<T>>(() => {
    const FormItemAll: ProColumnsType<T> = columns.filter(
      (_) => _.search !== false && !_.hideInSearch && _.valueType !== 'option'
    );
    return FormItemAll;
  }, [columns]);
  const [previousValues, setpreviousValues] = useState({});
  const [filters, setFilters] = useState({});
  const [sorter, setSorter] = useState({});
  const searchRef = useRef<SearchRef>(null);
  const sendSearch = (values: any, isReset = false) => {
    // 第二次调用时合并值
    let mergedValues = null;
    if (isReset) {
      mergedValues = values;
    } else {
      mergedValues = { ...previousValues, ...values };
    }
    setCurrent(1);
    reqFetch({ pageSize, current: 1, ...mergedValues }, filters, sorter);
    // 保存上一次的值
    setpreviousValues(mergedValues);
  };
  //刷新
  const reload = () => {
    reqFetch({ pageSize, current, ...previousValues }, filters, sorter);
  };
  //表格大小
  const [size, setSize] = useState<'middle' | 'large' | 'small'>('middle');
  const adjustSize = (val: 'middle' | 'large' | 'small') => setSize(val);
  const renderColumns = (columns: ProColumnsType<T>) => {
    return columns
      .filter((v) => !v.hideInTable)
      .map((column) => {
        if (!column.copyable || column.render) {
          return column;
        }

        return {
          ...column,
          render: (text: any) => {
            return (
              <>
                <span>{text}</span>
                <Icon
                  icon='CopyOutlined'
                  style={{ color: 'var(--ant-primary-color)', marginLeft: '10px' }}
                  onClick={() => {
                    copyText(text);
                  }}
                ></Icon>
              </>
            );
          },
        };
      });
  };
  useImperativeHandle(ref, () => ({
    reload,
    searchRef,
  }));
  return (
    <GlobalContext.Provider value={{ loading: tabLoading }}>
      {/* 顶部搜索 */}
      {search && (
        <div style={{ padding: '10px', background: '#fff', marginBottom: '15px' }}>
          <SearchBar
            ref={searchRef}
            search={search}
            formItems={searchFormItem}
            style={{ padding: '15px' }}
            layout='inline'
            onSearch={sendSearch}
          />
        </div>
      )}
      {/* 表格 */}
      <div style={{ padding: '10px', background: '#fff' }}>
        <Table
          {...tableProps}
          size={size}
          onChange={(page, filters, sorter) => {
            page && setPageSize(page.pageSize as any);
            page && setCurrent(page.current as any);
            setFilters(filters);
            setSorter(sorter);
            reqFetch({ pageSize: page.pageSize, current: page.current, ...previousValues }, filters, sorter);
          }}
          columns={renderColumns(columns)}
          loading={tabLoading}
          dataSource={data.data}
          pagination={{
            position: pagination ? pagination.position : ([] as any),
            total: data.total,
            pageSize,
            current,
          }}
          title={() => {
            return (
              <TableHeader
                search={search}
                refeshFuntion={reload}
                sizeFuntion={adjustSize}
                onMoreSearch={sendSearch}
                headerTitle={typeof headerTitle === 'function' ? headerTitle() : headerTitle}
                toolBarRender={
                  toolBarRender && toolBarRender().map((elemnet, index) => <div key={index}>{elemnet}</div>)
                }
                MoreFormItem={searchFormItem}
              />
            );
          }}
        />
      </div>
    </GlobalContext.Provider>
  );
});
export default ProTable;
